<template>
  <view>
    <cu-custom bgColor="bg-gradual-green" :isBack="true">
      <block @click="goBack" slot="backText">返回</block>
      <block slot="content">编辑课程</block>
    </cu-custom>

    <view style="margin-bottom: 130rpx;background-color: #FFFFFF;">
      <view style="width: 100%;padding: 0 30upx;background-color: #fff;">
        <input style="height: 100upx;line-height: 100upx;" type="text" v-model="names" placeholder="请输入训练主题" />
      </view>

      <view>
        <view style="width: 100%;padding: 0 30upx;background-color: #fff;margin-top: 20upx;">
          <view style="height: 100upx;display: flex;justify-content: space-between;">
            <view style="line-height: 100upx;display: flex;">
              <view style="width: 25upx;height: 25upx;background-color: #F0B55B;margin: 37.5upx 30upx 0 0;"></view>
              <view>
                热身训练
              </view>
            </view>
            <!-- <view>
              <button type="default" style="color: #C7C7C7;border: 1upx solid #C7C7C7;height: 60upx;line-height: 60upx;background-color: #fff;font-size: 24upx;margin-top: 20upx;">
                创建循环
              </button>
            </view> -->
          </view>
        </view>
        <template v-if="hotTraining.length">
          <block v-for="(item, index) in hotTraining" :key="index">
            <view class="xiong">
              <view class="huise u-f-ac relative">
                <view class="zuoz">
                  {{item.name}}
                </view>
                <view class="sanz" @click="toggle3(item, index, 'hotTraining')">
                  <text v-if="item.gropNum">{{item.gropNum}}组</text>X
                  <text v-if="item.numOfGroup">{{item.numOfGroup}}次</text>

                </view>
                <view class="shik" v-if="(item.devicesIdArray && item.devicesIdArray.length) || item.obstruction || item.restOfGroup"
                  @click="toggle3(item, index, 'hotTraining')">
                  <text v-if="item.devicesIdArray && item.devicesIdArray.length">{{item.devicesIdArray[0]}}.</text><text
                    v-if="item.obstruction">{{item.obstruction}}KG.</text><text v-if="item.restOfGroup">间休{{item.restOfGroup+'s'}}</text>
                </view>
                <view @click="isShow('hotTraining', index)" class="absoEmoji" :class="item.isShow ? 'cuIcon-fold' : 'cuIcon-unfold'"></view>

              </view>
              <template v-if="item.isShow">
                <view v-for="(item2, index2) in item.groupList" :key="index2" class="children-list u-f-ac">
                  <text class="cuIcon-title"></text>
                  <text class="list-items">{{item2['次数'] || '---'}}次</text>
                  <text class="list-items">{{item2['器械'] || '无器械'}}</text>
                  <text class="list-items">{{item2['阻力'] || '---'}}KG</text>
                  <text class="list-items" style="border-right: none;">{{item2['间休'] || '---'}}S</text>
                  <text @click="deleteItem('hotTraining' ,index, index2)" style="margin-left: 20rpx;" class="cuIcon-roundclose"></text>
                </view>
                <view @click="addItem('hotTraining', index)" class="u-f-ajc" style="color: #468BE3;padding-bottom: 30rpx;font-size: 24rpx;">
                  + 添加
                </view>
              </template>
            </view>
          </block>
        </template>

        <view @click="jump" :data-src='"/pagesA/trial_class/movement_list?id=hotTraining&planCourseId="+planCourseId+"&index="+index+"&experienceClass="+experienceClass'
          style="text-align: center;width: 100%;border-top: 1upx solid #F6F6F6;background-color: #fff;">
          <view style="color: #468BE3;min-height: 180upx;line-height: 180upx;">
            + 添加动作
          </view>
        </view>
      </view>

      <view>
        <view style="width: 100%;padding: 0 30upx;background-color: #fff;margin-top: 20upx;">
          <view style="height: 100upx;display: flex;justify-content: space-between;">
            <view style="line-height: 100upx;display: flex;">
              <view style="width: 25upx;height: 25upx;background-color: #46C3C6;;margin: 37.5upx 30upx 0 0;"></view>
              <view>
                正式训练
              </view>
            </view>
            <!-- <view>
              <button type="default" style="color: #C7C7C7;border: 1upx solid #C7C7C7;height: 60upx;line-height: 60upx;background-color: #fff;font-size: 24upx;margin-top: 20upx;">
                创建循环
              </button>
            </view> -->
          </view>
        </view>
        <template v-if="formalTraining.length">
          <block v-for="(item, index) in formalTraining" :key="index">
            <view class="xiong">
              <view class="huise u-f-ac relative">
                <view class="zuoz">
                  {{item.name}}
                </view>
                <view class="sanz" @click="toggle3(item, index, 'formalTraining')">
                  {{item.gropNum}}组 X {{item.numOfGroup+'次'}}
                </view>
                <view class="shik" v-if="(item.devicesIdArray && item.devicesIdArray.length) || item.obstruction || item.restOfGroup"
                  @click="toggle3(item, index, 'formalTraining')">
                  <text v-if="item.devicesIdArray && item.devicesIdArray.length">{{item.devicesIdArray[0]}}.</text>
                  <text v-if="item.obstruction">{{item.obstruction}}KG.</text>
                  <text v-if="item.restOfGroup">间休{{item.restOfGroup+'s'}}</text>
                </view>
                <view @click="isShow('formalTraining', index)" class="absoEmoji" :class="item.isShow ? 'cuIcon-fold' : 'cuIcon-unfold'"></view>

              </view>
              <template v-if="item.isShow">
                <view v-for="(item2, index2) in item.groupList" :key="index2" class="children-list u-f-ac">
                  <text class="cuIcon-title"></text>
                  <text class="list-items">{{item2['次数']}}次</text>
                  <text class="list-items">{{item2['器械'] || '无器械'}}</text>
                  <text class="list-items">{{item2['阻力']}}KG</text>
                  <text class="list-items" style="border-right: none;">{{item2['间休']}}S</text>
                  <text @click="deleteItem('formalTraining' ,index, index2)" style="margin-left: 20rpx;" class="cuIcon-roundclose"></text>
                </view>
                <view @click="addItem('formalTraining', index)" class="u-f-ajc" style="color: #468BE3;padding-bottom: 30rpx;font-size: 24rpx;">
                  + 添加
                </view>
              </template>
            </view>
          </block>
        </template>

        <view @click="jump" :data-src='"/pagesA/trial_class/movement_list?id=formalTraining&planCourseId="+planCourseId+"&index="+index+"&experienceClass="+experienceClass'
          style="text-align: center;width: 100%;border-top: 1upx solid #F6F6F6;background-color: #fff;">
          <view style="color: #468BE3;min-height: 180upx;line-height: 180upx;">
            + 添加动作
          </view>
        </view>
      </view>

      <view>
        <view style="width: 100%;padding: 0 30upx;background-color: #fff;margin-top: 20upx;">
          <view style="height: 100upx;display: flex;justify-content: space-between;">
            <view style="line-height: 100upx;display: flex;">
              <view style="width: 25upx;height: 25upx;background-color: #799AF7;;margin: 37.5upx 30upx 0 0;"></view>
              <view>
                放松整理
              </view>
            </view>
            <!-- <view>
              <button type="default" style="color: #C7C7C7;border: 1upx solid #C7C7C7;height: 60upx;line-height: 60upx;background-color: #fff;font-size: 24upx;margin-top: 20upx;">
                创建循环
              </button>
            </view> -->
          </view>
        </view>
        <template v-if="relaxTraining.length">
          <block v-for="(item, index) in relaxTraining" :key="index">
            <view class="xiong">
              <view class="huise u-f-ac relative">
                <view class="zuoz">
                  {{item.name}}
                </view>
                <view class="sanz" @click="toggle3(item, index, 'relaxTraining')">
                  {{item.gropNum}}组 X {{item.numOfGroup+'次'}}
                </view>
                <view class="shik" v-if="(item.devicesIdArray && item.devicesIdArray.length) || item.obstruction || item.restOfGroup"
                  @click="toggle3(item, index, 'relaxTraining')">
                  <text v-if="item.devicesIdArray && item.devicesIdArray.length">{{item.devicesIdArray[0]}}.</text><text
                    v-if="item.obstruction">{{item.obstruction}}KG.</text><text v-if="item.restOfGroup">间休{{item.restOfGroup+'s'}}</text>
                </view>
                <view @click="isShow('relaxTraining', index)" class="absoEmoji" :class="item.isShow ? 'cuIcon-fold' : 'cuIcon-unfold'"></view>

              </view>
              <template v-if="item.isShow">
                <view v-for="(item2, index2) in item.groupList" :key="index2" class="children-list u-f-ac">
                  <text class="cuIcon-title"></text>
                  <text class="list-items">{{item2['次数']}}次</text>
                  <text class="list-items">{{item2['器械'] || '无器械'}}</text>
                  <text class="list-items">{{item2['阻力']}}KG</text>
                  <text class="list-items" style="border-right: none;">{{item2['间休']}}S</text>
                  <text @click="deleteItem('relaxTraining' ,index, index2)" style="margin-left: 20rpx;" class="cuIcon-roundclose"></text>
                </view>
                <view @click="addItem('relaxTraining', index)" class="u-f-ajc" style="color: #468BE3;padding-bottom: 30rpx;font-size: 24rpx;">
                  + 添加
                </view>
              </template>
            </view>
          </block>
        </template>

        <view @click="jump" :data-src='"/pagesA/trial_class/movement_list?id=relaxTraining&planCourseId="+planCourseId+"&index="+index+"&experienceClass="+experienceClass'
          style="text-align: center;width: 100%;border-top: 1upx solid #F6F6F6;background-color: #fff;">
          <view style="color: #468BE3;min-height: 180upx;line-height: 180upx;">
            + 添加动作
          </view>
        </view>
      </view>

      <editPopup ref="eidtPopup" :item="editDetail" :index="editDetailIndex" @editPopups="editPopups" :names="editNames" />

    </view>

    <button @click="goPages" type="default" style="width: 80%;margin-left: 10%;background-color: #39BB9E;color: #FFFFFF;position: fixed;bottom: 50upx;">{{isEdit ? '修改' : '保存'}}</button>
  </view>

</template>

<script>
  import editPopup from "../../components/edit-popup/edit-popup.vue"
  export default {
    components: {
      editPopup,
    },
    data() {
      return {
        names: '',
        hotTraining: [],
        formalTraining: [],
        relaxTraining: [],
        isEdit: false,
        planCourseId: '',
        index: '',
        experienceClass: '',
        datas: {},

        editDetail: {},
        editDetailIndex: 0,
        editNames: '',
      }
    },
    async onLoad(e) {
      console.log(e)
      this.experienceClass = e.experienceClass;
      if (e.planCourseId) {
        console.log('修改界面')
        this.isEdit = true
        this.index = e.index;
        this.planCourseId = e.planCourseId;
        await this.getData(e.planCourseId);
      }
      if (uni.getStorageSync('names') || uni.getStorageSync('hotTraining') || uni.getStorageSync('formalTraining') ||
        uni.getStorageSync('relaxTraining')) {
        console.log('缓存有值')
        this.names = uni.getStorageSync('names');
        this.hotTraining = uni.getStorageSync('hotTraining');
        this.formalTraining = uni.getStorageSync('formalTraining');
        this.relaxTraining = uni.getStorageSync('relaxTraining');
      }
      if (e.id && this[e.id]) {
        console.log('从动作列表回来')
        this[e.id] = [...this[e.id], ...uni.getStorageSync("numsDetail")]
      } else if (e.id && !this[e.id]) {
        this[e.id] = uni.getStorageSync("numsDetail")
      }
    },
    methods: {
      toggle3(item, index, names) {
        this.editDetail = item
        this.editDetailIndex = index
        this.editNames = names
        console.log('点击进去的值', this.editDetail, this.editDetailIndex)
        this.$refs.eidtPopup.toggle3();
      },
      editPopups(e) {
        // 需要修改子数组
        let groupList = []
        let groupListItem = {
          "次数": e.editDetail.numOfGroup,
          "器械": e.editDetail.devicesIdArray[0] || '',
          "阻力": e.editDetail.obstruction,
          "间休": e.editDetail.restOfGroup,
        }
        console.log(e)
        for (let i = 1; i <= e.editDetail.gropNum; i++) {
          groupList.push(groupListItem)
        }
        e.editDetail.groupList = groupList
        this[e.names].splice([e.editDetailIndex], 1, e.editDetail);
      },
      async getData(planCourseId) {
        let {
          data: {
            datas
          }
        } = await this.$myRuquest({
          url: "/coach/training/getTrainingPlanCourseDetail",
          data: {
            planCourseId
          }
        })
        this.datas = datas;
        this.names = datas.name;
        console.log(this.datas)
        let addIsShow = (item) => {
          if (datas[item].length) {
            console.log('给获取的值添加isShow')
            datas[item].forEach(item => this.$set(item, 'isShow', false))
          }
        }
        addIsShow('hotTraining')
        addIsShow('formalTraining')
        addIsShow('relaxTraining')
        this.hotTraining = datas.hotTraining;
        this.formalTraining = datas.formalTraining;
        this.relaxTraining = datas.relaxTraining;

        console.log(this.hotTraining)
        console.log(this.formalTraining)
        console.log(this.relaxTraining)
      },
      async redirectTo() {
        uni.setStorageSync("names", '');
        uni.setStorageSync("numsDetail", '');
        uni.setStorageSync("hotTraining", '');
        uni.setStorageSync("formalTraining", '');
        uni.setStorageSync("relaxTraining", '');
        if (this.isEdit) {
          uni.redirectTo({
            url: `/pagesA/Preparation_plan/Class_situation?index=${this.index}&id=${this.planCourseId}&experienceClass=${this.experienceClass}`
          })
        } else {
          let {
            data: {
              datas: {
                trainingPlanCourseList
              }
            }
          } = await this.$myRuquest({
            url: "/coach/training/getTrainingPlanCourseList",
            data: {
              planId: uni.getStorageSync("planId"),
              memberId: uni.getStorageSync("phyUser").userId,
              experience: this.experienceClass,
            },
          })
          uni.redirectTo({
            url: `/pagesA/Preparation_plan/Class_situation?index=${trainingPlanCourseList.length}&id=${trainingPlanCourseList[trainingPlanCourseList.length-1].id}&experienceClass=${this.experienceClass}`
          });
        }
      },
      async edit() {
        let data = {
          "id": this.datas.id,
          "experienceClass": parseInt(this.experienceClass),
          "formalTraining": this.formalTraining,
          "hotTraining": this.hotTraining,
          "memberId": uni.getStorageSync("phyUser").userId,
          "name": this.names,
          "planId": parseInt(uni.getStorageSync("planId")),
          "relaxTraining": this.relaxTraining,
          "userId": uni.getStorageSync("openid"),
        }
        console.log('111---------------------------------', data)
        for (let i in data) {
          if (!data[i]) {
            uni.showToast({
              title: "参数不完整~",
              icon: 'loading'
            })
            return
          } else {
            uni.showLoading({
              title: "修改课程中..."
            })
          }
        }
        let res = await this.$myRuquest({
          url: "/coach/training/updateTrainingPlanCourse",
          method: "PUT",
          data,
          header: {
            'Content-Type': 'application/json',
          },
        })
        this.redirectTo();
      },
      async submit() {
        let data = {
          "experienceClass": this.experienceClass,
          "name": this.names,
          "memberId": uni.getStorageSync("phyUser").userId,
          "planId": '',
          "userId": uni.getStorageSync("openid"),
          "hotTraining": [],
          "formalTraining": [],
          "relaxTraining": [],
        }
        if (this.experienceClass == '2') data.planId = parseInt(uni.getStorageSync("planId"))
        else if (this.experienceClass == '1') data.planId = ''
        let computedArr = (names) => {
          this[names].forEach((item, index) => {
            let obj = {
              "actionId": 0,
              "gropNum": 0,
              "groupList": [],
              "introduce": "string",
              "name": "string",
              "numOfGroup": 0,
              "obstruction": 0,
              "restOfGroup": 0,
              "timeOfGroup": 0,
            }
            obj.id = item.id
            obj.gropNum = item.gropNum
            obj.introduce = item.introduce
            obj.name = item.name
            obj.numOfGroup = item.numOfGroup
            obj.obstruction = item.obstruction
            obj.restOfGroup = item.restOfGroup
            obj.timeOfGroup = item.timeOfGroup
            obj.groupList = item.groupList
            data[names].push(obj);
          })
        }
        if (this.hotTraining.length) computedArr('hotTraining')
        if (this.formalTraining.length) computedArr('formalTraining')
        if (this.relaxTraining.length) computedArr('relaxTraining')
        console.log('查看要传输的数据：', data)

        for (let i in data) {
          if (!data[i] && !data.name) {
            uni.showToast({
              title: "请输入训练主题",
              icon: 'loading'
            })
            return
          } else {
            uni.showLoading({
              title: "保存课程中..."
            })
          }
        }
        let res = await this.$myRuquest({
          url: "/coach/training/addTrainingPlanCourse",
          method: "POST",
          data,
          header: {
            'Content-Type': 'application/json',
          },
        })
        uni.hideLoading()
        this.redirectTo()
      },
      async goPages() {
        if (this.isEdit) await this.edit()
        else await this.submit()
      },
      goBack() {
        uni.setStorageSync("names", '');
        uni.setStorageSync("numsDetail", '');
        uni.setStorageSync("hotTraining", '');
        uni.setStorageSync("formalTraining", '');
        uni.setStorageSync("relaxTraining", '');
        uni.navigateBack({
          delta: 1
        });
      },

      isShow(id, index) {
        this[id][index].isShow = !this[id][index].isShow;
      },
      deleteItem(name, index, index2) {
        this[name][index].groupList.splice(index2, 1);
        this[name][index].gropNum = this[name][index].groupList.length

        if (!this[name][index].groupList.length) this[name].splice(index, 1);
      },
      addItem(name, index) {
        let item = this[name][index].groupList
        item.push(item[item.length - 1])
      },
      jump(e) {
        console.log(e.currentTarget.dataset.src)
        uni.setStorageSync("names", this.names);
        uni.setStorageSync("hotTraining", this.hotTraining);
        uni.setStorageSync("formalTraining", this.formalTraining);
        uni.setStorageSync("relaxTraining", this.relaxTraining);
        if (e.currentTarget.dataset.src == 'Not-yet-open') {
          uni.showModal({
            title: '提示',
            content: '功能即将开放',
            showCancel: false,
            confirmColor: "#DD524D",
            success() {
              return
            }
          })
        } else {
          uni.navigateTo({
            url: e.currentTarget.dataset.src
          });
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  .xiong {
    width: 92%;
    margin: 0 auto;
    background: #F1F1F1;
    margin-bottom: 10rpx;
  }

  .huise {
    width: 100%;
    padding: 20rpx 30rpx;
  }

  .zuoz {
    // position: absolute;
    // left: 30rpx;
    // max-width: 140rpx;
    font-size: 28upx;
  }

  .sanz {
    font-size: 24upx;
    background: #86939f;
    padding: 14upx;
    color: #ffffff;
    margin-left: 20upx;
  }

  .shik {
    border: #86939F 1upx solid;
    font-size: 24upx;
    padding: 12upx;
    color: #abaeb3;
  }

  .children-list {
    font-size: 20rpx;
    padding: 40rpx 0 50rpx 70rpx;
    box-sizing: border-box;
    color: #777;
    font-size: 24rpx;

    .list-items {
      padding: 0 20rpx;
      border-right: 1px solid #ccc;
    }
  }

  .absoEmoji {
    position: absolute;
    right: 40rpx;
  }
</style>
